package com.algorithm2;

import java.util.Arrays;

public class HeapSort2 {

    private static void buildHeap(int[] a,int n){
        for(int i=(n/2);i>=1;--i){
            heapify(a,n,i);
        }
    }

    public static void heapify(int[] a,int n,int i){
        while(true){
            int maxPos = i;
            if(i*2<=n && a[i]<a[i*2])
                maxPos = i*2;
            if(i*2+1<=n && a[maxPos]<a[i*2+1])
                maxPos = i*2+1;
            if(maxPos == i)
                break;
            swap(a,i,maxPos);
            i = maxPos;
        }
        System.out.println("heapify i为："+"-->"+i +"-->"+ Arrays.toString(a));

    }
    private static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    public static void sort(int[] a,int n){
        buildHeap(a,n);
        System.out.println("buildHeap finish "+ Arrays.toString(a));
        int k  = n;
        while(k>1){
            swap(a,1,k);
            System.out.println(k+"-->交换完数据:"+Arrays.toString(a));
            k--;
            heapify(a,k,1);
        }
    }

    public static void main(String[] args){
        int[] array = new int[]{0,8, 9, 3,10, 2, 4, 5, 6, 7, 1};
        //buildHeap(array,array.length-1);
        //System.out.println("构建堆:" + Arrays.toString(array));
        sort(array,array.length-1);
        System.out.println("排序后:" + Arrays.toString(array));
    }
}
